//@ts-nocheck
import Axios from 'axios'
import {  showFailToast } from 'vant';

function requestFactory(httpClient) {
  httpClient.interceptors.request.use(
    (opts) => {
      //const token = store.get(AUTH_TOKEN)
     
        opts.headers.Authorization = 'Bearer 7e5eca549809495ca4e86a3f64d57538'
      
      return opts
    },
    (error) => Promise.reject(error)
  )
}
  const errorCode = {
    '401': '认证失败，无法访问系统资源',
    '403': '当前操作没有权限',
    '404': '访问资源不存在',
    default: '系统未知错误，请反馈给管理员'
  }
  const ignoreMsgs = [
    '无效的刷新令牌', // 刷新令牌被删除时，不用提示
    '刷新令牌已过期' // 使用刷新令牌，刷新获取新的访问令牌时，结果因为过期失败，此时需要忽略。否则，会导致继续 401，无法跳转到登出界面
  ]
  

function responseFactory(httpClient) {
  httpClient.interceptors.response.use(
    async (response) => {
      let { data } = response
      const config = response.config
      if (!data) {
        // 返回“[HTTP]请求没有返回值”;
        throw new Error()
      }
     
      // 未设置状态码则默认成功状态
      // 二进制数据则直接返回，例如说 Excel 导出
      if (
        response.request.responseType === 'blob' ||
        response.request.responseType === 'arraybuffer'
      ) {
        // 注意：如果导出的响应为 json，说明可能失败了，不直接返回进行下载
        if (response.data.type !== 'application/json') {
          return response.data
        }
        data = await new Response(response.data).json()
      }
      const code = data.code
      // 获取错误信息
      const msg = data.msg || errorCode[code]
      if(msg) {
        showFailToast(msg)
        return Promise.reject(data)
      } else {
        return data
      }

    },
    (error) => {
      return Promise.reject(error)
    }
  )
}

function clientFactory(options = {}) {
  const client = Axios.create(options)
 // requestFactory(client)
  responseFactory(client)
  return client
}

const request = clientFactory({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 1000 * 300, // 5min
})

export default request
